# try:
#     print("code started")
# except KeyError as e:
#     print("key Error")
# except IndexError as e:
#     print("Index Error")
# else:
#     print("没有发生异常的情况")
# finally:
#     print("finish")
#     # 如果finally 中存在return，那最后返回的就是这里的return

class Sample:
    def __enter__(self):
        # 获取资源
        print("enter")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # 释放资源
        print("exit")

    def do_something(self):
        print("do something")


# 上下文管理器协议，with语句 当开始时候调用__enter__，结束时候调用__exit__
with Sample() as s:
    s.do_something()
